package pers.vic.blog.module.front.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import pers.vic.blog.config.es.model.EsBlogArticleModel;
import pers.vic.blog.constant.GlobalFieldParams;
import pers.vic.blog.module.api.mapper.BlogArticleMapper;
import pers.vic.blog.module.api.model.*;
import pers.vic.blog.module.api.service.*;
import pers.vic.blog.module.front.mapper.BlogHomeMapper;
import pers.vic.blog.module.front.model.BlogHomeModel;
import pers.vic.blog.module.front.model.RightAsideModel;
import pers.vic.blog.module.front.model.ShowTopicModel;
import pers.vic.boot.base.lookup.Lookup;
import pers.vic.boot.base.model.BaseEntity;
import pers.vic.boot.base.model.PageInfo;
import pers.vic.elasticsearch.model.EsLookup;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * @author Vic.xu
 * @description:
 * @date: 2020/5/25 0025 17:34
 */
@Service
public class BlogHomeService {

    @Autowired
    private BlogHomeMapper blogHomeMapper;

    @Autowired
    private BlogCategoryService blogCategoryService;

    @Autowired
    private BlogTopicService blogTopicService;

    @Autowired
    private BlogTagService blogTagService;

    @Autowired
    private BlogArticleService blogArticleService;

    @Autowired
    private BlogArticleMapper blogArticleMapper;

    @Autowired
    private BlogArticleFileService blogArticleFileService;


    @Autowired
    private GlobalConfigService globalConfigService;

    /**
     * 首页展示
     */
    public BlogHomeModel homeQuery() {
        BlogHomeModel blogHomeModel = new BlogHomeModel();
        //最新列表
        List<BlogArticle> newest = newest();
        blogHomeModel.setNewest(newest);
        //专题列表
        blogHomeModel.setShowTopics(topicShows());
        return blogHomeModel;
    }

    /**
     * 查询出右侧公共部分的数据
     */
    public RightAsideModel queryRight(){
        RightAsideModel rightAsideModel = new RightAsideModel();
        // all enable category
        rightAsideModel.setBlogCategories(enableCategoryList());
        //all enable topic
        rightAsideModel.setBlogTopics(enableTopicList());
        //all enable tag
        rightAsideModel.setBlogTags(enableTagList());
        //all file
        rightAsideModel.setBlogFiles(enableFileList());

        //links 友情链接
        rightAsideModel.setLinks(links());
        return  rightAsideModel;

    }

    /**
     * 友情链接
     */
    private Map<String, String> links(){
        Map<String, String> result = new HashMap<>(32);
        GlobalConfig config = globalConfigService.getByCode(GlobalFieldParams.GlobalConfigCodeEnum.links);
        if (StringUtils.isNotBlank(config.getContent())) {
            String[] links = config.getContent().split(";");
            for (String link : links) {
                String[] ss = link.split("=");
                if (ss.length == 2) {
                    result.put(ss[0], ss[1]);
                }
            }
        }
        return result;
    }

    /**
     * all enable tag
     * @return
     */
    public List<BlogCategory> enableCategoryList(){
        List<BlogCategory> list = blogCategoryService.list(enableLookup(BlogCategory::new));
        return list;
    }
    /**
     * all enable tag
     * @return
     */
    public List<BlogTag> enableTagList(){
        List<BlogTag> list = blogTagService.list(enableLookup(BlogTag::new));
        return list;
    }
    /**
     * all enable topic
     * @return
     */
    public List<BlogTopic> enableTopicList(){
        List<BlogTopic> list = blogTopicService.list(enableLookup(BlogTopic::new));
        return list;
    }

    /**
     * 全部文正归档列表
     */
    public List<BlogArticleFile> enableFileList(){
        List<BlogArticleFile> list= blogArticleFileService.list(enableLookup(BlogArticleFile::new));
        return list;
    }

    /**
     * 最新列表
     *
     * @return
     */
    private List<BlogArticle> newest() {
        BaseEntity articleLookup = enableLookup(BlogArticle::new);
        articleLookup.setSortColumn("createTime");
        articleLookup.setSortOrder("DESC");
        PageInfo<BlogArticle> articlePageInfo = blogArticleService.page(articleLookup);
        return articlePageInfo.getDatas();
    }

    /**
     * 首页展示的专题和专题下的文章列表
     *
     * @return
     */
    private List<ShowTopicModel> topicShows() {
        //每个专题下最多取多少条
        int num = 10;
        return blogHomeMapper.topicShows(num - 1);
    }

    /**
     * 查询文章列表
     * @param lookup
     * @return
     */
    public PageInfo<BlogArticle> page(Lookup lookup){
        PageInfo<BlogArticle> page = blogArticleService.page(lookup);
        page.setLookup(lookup);
        return page;
    }


    /**
     * put enable tag list to model
     * @param model
     */
    public void putTagToModel(Model model){
        model.addAttribute("tags", enableTagList());
    }

    /**
     * put current category model
     * @param model
     */
    public void putCurrentCategoryToModel(Model model, BlogArticle lookup){
        Integer cid = lookup.getCategoryId();
        if(cid != null){
            model.addAttribute("category", blogCategoryService.findById(cid));
        }
    }

    /**
     * put current topic model
     * @param model
     */
    public void putCurrentTopicToModel(Model model, BlogArticle lookup){
        Integer tid = lookup.getTopicId();
        if(tid != null){
            model.addAttribute("topic", blogTopicService.findById(tid));
        }
    }

    /**
     * 构建可用的查询条件  根据构造函数
     * @param supplier
     * @param <T>
     * @return
     */
    private <T extends BaseEntity> T enableLookup(Supplier<? extends BaseEntity> supplier) {
        BaseEntity lookup = supplier.get();
        lookup.setEnable(true);
        return (T) lookup;
    }

    /**
     * 获取博文详情  并增加阅读次数
     * @param id
     * @return
     */
    public BlogArticle findById(int id) {
        BlogArticle blogArticle = blogArticleService.findById(id);
        try {
            BlogArticle article = new BlogArticle();
            article.setId(id);
            article.setReadNum(blogArticle.getReadNum() + 1);
            blogArticleMapper.update(article);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return blogArticle;
    }

    /**
     * 根据关键字搜索
     * @param lookup
     * @return
     * @throws IOException
     */
    public PageInfo<EsBlogArticleModel> search(EsLookup<EsBlogArticleModel> lookup) throws IOException {
        return blogArticleService.search(lookup);
    }
}
